package service

import (
	"context"
	"encoding/json"

	"github.com/aws/aws-sdk-go-v2/aws"
	"github.com/aws/aws-sdk-go-v2/config"
	"github.com/aws/aws-sdk-go-v2/credentials"
	"github.com/aws/aws-sdk-go-v2/service/ec2"
)

type AwsService struct {
	BaseConfig
	cfg aws.Config
}

func (that *AwsService) GetInstances() error {
	var (
		ctx context.Context
		err error
	)
	that.cfg, err = config.LoadDefaultConfig(ctx,
		config.WithCredentialsProvider(credentials.NewStaticCredentialsProvider(that.AccessKeyId, that.AccessKeySecret, "")),
	)
	if err != nil {
		return err
	}
	return nil
}

func (that *AwsService) GetEcsInfo(extend map[string]any) map[string]any {
	client := ec2.NewFromConfig(that.cfg, func(o *ec2.Options) {
		o.Region = extend["region_id"].(string)
	})

	result, err := client.DescribeInstances(context.TODO(), &ec2.DescribeInstancesInput{InstanceIds: []string{extend["instance_id"].(string)}})
	if err != nil {
		return nil
	}
	origin_data, _ := json.Marshal(result.Reservations[0].Instances[0])

	Info := map[string]any{
		"account_id":  extend["account_id"],
		"instance_id": *result.Reservations[0].Instances[0].InstanceId,
		"region_id":   extend["region_id"],
		"add_time":    *result.Reservations[0].Instances[0].LaunchTime,
		"end_time":    nil,
		"ip_address":  *result.Reservations[0].Instances[0].PublicIpAddress,
		"origin_data": string(origin_data),
	}

	return Info
}
